import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import { createServer as createViteServer } from "vite";
import { WebSocketServer } from "ws";
import chalk from "chalk";
import open from 'open';


async function createServer() {
  const app = express();
  let vueSocket = null;

  app.use(cors());
  app.use(bodyParser.urlencoded({ extended: true })); // 是否进行url解码
  app.use(bodyParser.json()); // 将数据转换为json格式

  app.post("/axure/receiveData", (req, res) => {
    // console.log("xxxx", req.query, req.body);
    vueSocket.send(JSON.stringify(req.body), () => {
      res.send(JSON.stringify({ code: 200, message: "成功" }));
    });
  });

  // 以中间件模式创建 Vite 服务器
  const vite = await createViteServer({
    server: { middlewareMode: true, open: '/' },
    // appType: "custom", // 不引入 Vite 默认的 HTML 处理中间件
    appType: "spa", // 不引入 Vite 默认的 HTML 处理中间件
  });

  // 将 vite 的 connect 实例作中间件使用
  app.use(vite.middlewares);

  const wss = new WebSocketServer({ port: 4001 });
  wss.on("connection", (wsReq) => {
    console.log("server connection");
    vueSocket = wsReq;
    vueSocket.send(JSON.stringify({ data: "test message" }));

    wsReq.on("close", function (reasonCode, description) {
      console.log(
        new Date() + " Peer " + wsReq.remoteAddress + " disconnected."
      );
    });
  });

  // 开启监听
  app.listen(4000, () => {
    console.log(`服务器启动成功~ ${chalk.green("http://localhost:4000")}`);
    open("http://localhost:4000");
  });
}

createServer();
